import math
from ._global import EPSILON

class Vector:

    def __init__(self, lst):
        self._values = list(lst)

    @classmethod
    def zero(cls, dim):
        """返回一个dim维的零向量"""
        return cls([0]*dim)

    def norm(self):
        """返回向量的模"""
        return math.sqrt(sum(e**2 for e in self))

    def normalize(self):
        """返回向量的单位向量"""
        if self.norm() < EPSILON:
            raise ZeroDivisionError("normalize error! norm is zero.")
        return 1/self.norm() * Vector(self._values)

    def __getitem__(self, index):
        """取向量的第index个元素"""
        return self._values[index]

    def __len__(self):
        """返回常量长度"""
        return len(self._values)

    def __add__(self, another):
        """加法"""
        assert len(self) == len(another), \
            "Error in adding, Length of vectors must bu same"
        #return Vector([a+b for a, b in zip(self._values, another._values)])
        return Vector([a + b for a, b in zip(self, another)])

    def __sub__(self, another):
        """减法"""
        assert len(self) == len(another), \
            "Error in subtracting, Length of vectors must bu same"
        return Vector([a - b for a, b in zip(self, another)])

    def dot(self, another):
        """向量的点乘, 返回结果标量"""
        assert len(self) == len(another), \
            "Error in subtracting, Length of vectors must bu same"
        return sum(a*b for a, b in zip(self, another))

    def __mul__(self, k):
        """乘法 self * k"""
        return Vector([k*e for e in self])

    def __rmul__(self, k):
        """乘法 k * self"""
        return Vector([k*e for e in self])

    def __pos__(self):
        """取正"""
        return 1*self

    def __neg__(self):
        """取负"""
        return -1*self

    def __iter__(self):
        """返回向量的迭代器"""
        return self._values.__iter__()

    def __repr__(self):
        return "Vector{}".format(self._values)

    def __str__(self):
        return "({})".format(", ".join(str(e) for e in self._values))
